#!/bin/bash
# Copyright (C) 2024-2025 KoudaiPC Computer Technologies Co., Ltd.
# script name: huangdi-host-setup-armsr-armv8-efi-image.sh
# author: david921518@qq.com

# 1. Enable NBD on the host
/sbin/modprobe nbd max_part=8

# 2. Connect the QCOW2 as a network block device
qemu-nbd --connect=/dev/nbd0 ./kpcos-huangdi-1.1-armsr-armv8-generic-ext4-combined-efi-4g.qcow2
sleep 1

# 3. Fix qcow2 image gpt
rm -f /tmp/parted_info
/sbin/parted --script /dev/nbd0 p 2>&1 | tee -a /tmp/parted_info
# gpt warning
if grep -Eq 'fix the GPT' /tmp/parted_info;then
  echo -e "OK\nFix\n" | /sbin/parted ---pretend-input-tty /dev/nbd0 print 1>/dev/null
  rm -f /tmp/parted_info
fi

# 4. enlarge partition
/sbin/parted /dev/nbd0 resizepart 2 100%
/sbin/parted /dev/nbd0 print
sleep 1

# 5. enlarge e2fs partition
export loop_device=$(/sbin/losetup -f)
/sbin/losetup $loop_device /dev/nbd0p2
/sbin/resize2fs -f $loop_device
/sbin/losetup -d $loop_device

# 6. Mount the partition from the VM
mount /dev/nbd0p2 /mnt/huangdi

# 7. Copy target scripts to mounted point
mkdir -p /mnt/huangdi/root/firstboot
cp -af ../guest /mnt/huangdi/root/firstboot/
cp -af ../root /mnt/huangdi/root/firstboot/
cp -af ../root/etc/rc.local /mnt/huangdi/etc/rc.local
cp -af ../root/etc/init.d/* /mnt/huangdi/etc/init.d/
cp -af ../root/etc/rc.d/* /mnt/huangdi/etc/rc.d/
chown root:root /mnt/huangdi/etc/init.d -R
chown root:root /mnt/huangdi/etc/rc.d -R
chown root:root /mnt/huangdi/root/firstboot -R

# 8. Unmount
umount /mnt/huangdi/

# 9. Disconnect
qemu-nbd --disconnect /dev/nbd0
sleep 1
/sbin/rmmod nbd

